using System;
using System.Collections.Generic;
using System.Text;
using FireStarter.Base;
using FireStarter.Base.BusinessObjectMerger;
using FireStarterModeller.BO;
using Habanero.Base;

namespace Firestarter.DB.Schema.Logic
{
    public class ChangeTypeTreeInspector
    {
        public static Dictionary<IBusinessObject, ChangeType> GetAllPendingChangeTypes(IBusinessObject businessObject)
        {
            Dictionary<IBusinessObject, ChangeType> allPendingChangeTypes = new Dictionary<IBusinessObject, ChangeType>();
            if (businessObject == null) return allPendingChangeTypes;
            IMergableBo mergableBo = (IMergableBo)businessObject;
            BusinessObjectTreeTraverser traverser = new BusinessObjectTreeTraverser();
            traverser.TraverseTree(businessObject, 1, delegate(IBusinessObject bo)
            {
                Dictionary<IBusinessObject, ChangeType> allPendingChangeTypesForChild = GetAllPendingChangeTypes(bo);
                foreach (KeyValuePair<IBusinessObject, ChangeType> pair in allPendingChangeTypesForChild)
                {
                    allPendingChangeTypes.Add(pair.Key, pair.Value);
                }
            });
            ChangeType parentChangeType = GetCombinedChangeType(allPendingChangeTypes);
            parentChangeType |= (mergableBo).PendingChangeType;
            allPendingChangeTypes.Add(businessObject, parentChangeType);
            return allPendingChangeTypes;
        }

        public static ChangeType GetCombinedChangeType(Dictionary<IBusinessObject, ChangeType> allPendingChangeTypes)
        {
            ChangeType combinedChangeType = 0;
            foreach (KeyValuePair<IBusinessObject, ChangeType> pair in allPendingChangeTypes)
            {
                if (combinedChangeType == ChangeType.All) break;
                combinedChangeType |= pair.Value;
            }
            return combinedChangeType;
        }

        //public Dictionary<IBusinessObject, ChangeType> GetAllPendingChangeTypes(IBusinessObject businessObject)
        //{
        //    ChangeType allPendingChangeTypes = ((IMergableBo)businessObject).PendingChangeType;
        //    BusinessObjectRelationshipTraverser traverser = new BusinessObjectRelationshipTraverser();
        //    traverser.AddSingleRelationshipToTraverse(typeof(Table), "DBPrimaryKey");
        //    traverser.TraverseChildren(businessObject, delegate(IBusinessObject bo, IRelationship relationship)
        //    {
        //        IMergableBo mergableBo = (IMergableBo)bo;
        //        allPendingChangeTypes |= mergableBo.PendingChangeType;
        //    });
        //    return new Dictionary<IBusinessObject, ChangeType>();
        //}
    }
}
